package org.formal.common.controller;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.formal.common.base.BaseEntity;
import org.formal.common.base.BaseService;
import org.formal.common.data.CodeEnum;
import org.formal.common.data.ResultData;
import org.formal.common.page.Pagination;
import org.formal.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * 公用增删改查
 * @author jiangyan
 *
 * @param <E>
 */
public class BaseController<E extends BaseEntity> {

	@SuppressWarnings("unchecked")
	private Class<E> entityClass = (Class<E>) ((ParameterizedType) getClass()
			.getGenericSuperclass()).getActualTypeArguments()[0];

	@Autowired
	protected BaseService<E> baseService;

	/**
	 * 如果page 中E对象 为空,则获取分页数据
	 * 否则根据字段 和值进行 模糊查询
	 * 
	 * @param
	 * @return
	 */
	@GetMapping(value = "/list/page")
	public Pagination<E> getListPage(Pagination<E> page,E entity,String order, String sort) {
		Example example = new Example(entityClass);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("isDelete", "0");
		JSONObject object = (JSONObject) JSON.toJSON(entity);
		getCriteriaParam(object, criteria);
		if (StringUtils.isNotEmpty(order)) {
			if (StringUtils.isEmpty(sort)) {
				example.orderBy(order);
			} else {
				example.setOrderByClause(humpToUnderline(order, sort));
			}
		}
		PageHelper.startPage(page.getPageNum(), page.getPageSize());
		List<E> rows = this.baseService.selectByExample(example);
		return new Pagination<E>(rows);
	}


	/**
	 * 获取所有数据
	 */
	@GetMapping(value = "/list")
	public List<E> getList(String order, String sort,Map<String,Object> param) {
		Example example = new Example(entityClass);
		Criteria criteria = example.createCriteria();
		criteria.andEqualTo("isDelete", "0");
		JSONObject object = new JSONObject(param);
		if(object != null) {
			getCriteriaParam(object, criteria);
		}
		if (StringUtils.isNotEmpty(order)) {
			if (StringUtils.isEmpty(sort)) {
				example.orderBy(order);
			} else {
				example.setOrderByClause(humpToUnderline(order, sort));
			}
		}
		List<E> rows = this.baseService.selectByExample(example);
		return rows;
	}


	/**
	 * 根据id获取权限数据
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/list/{id}")
	public E getEntityById(@PathVariable("id") String id) {
		return this.baseService.selectByKey(id);
	}

	/**
	 * 保存权限信息
	 * @param entity
	 */
	@PostMapping(value = "/save")
	public ResultData saveEntity(E entity) {
		ResultData resultData = new ResultData();
		try {
			this.baseService.save(entity);
			resultData.setSuccess(true);
			resultData.setCode(CodeEnum.SUCCESS);
			resultData.setMessage("保存成功");
		} catch (Exception e) {
			resultData.setSuccess(false);
			resultData.setMessage("保存失败");
			resultData.setCode(CodeEnum.ERROR);
		}
		return resultData;
	}

	public ResultData getResultData(boolean isSuccess, String message) {
		ResultData resultData = new ResultData();
		resultData.setSuccess(isSuccess);
		if (isSuccess) {
			resultData.setCode(CodeEnum.SUCCESS);
			resultData.setMessage(message);
		} else {
			resultData.setCode(CodeEnum.ERROR);
			resultData.setMessage(message);
		}
		return resultData;
	}

	/**
	 * 删除权限信息
	 */
	@PostMapping(value = "/delete")
	public ResultData delete(@RequestParam("id") String id) {
		ResultData resultData = null;
		try {
			this.baseService.delete(id);
			resultData = this.getResultData(true, "删除成功");
		} catch (Exception e) {
			resultData = this.getResultData(false, "删除失败");
		}
		return resultData;
	}
	
	/*
	 * 参数jsonObject 查询条件拼接
	 */
	private void getCriteriaParam (JSONObject object, Criteria criteria) {
		for (Entry<String, Object> entry : object.entrySet()) {
			Object value = entry.getValue();
			if(StringUtils.isNotEmpty(value)) {
				if(value instanceof Boolean) {
					value = (boolean) value?1:0;
					criteria.andEqualTo(entry.getKey(), value);
				}else {
					criteria.andLike(entry.getKey(), value + "%");
				}
			}
		}
	}
	
	/***
	 * 驼峰命名转为下划线命名
	 * @param sort 
	 * 
	 * @param para
	 *        驼峰命名的字符串
	 */

	public String humpToUnderline(String order, String sort){
		StringBuilder sb = new StringBuilder(order);
		int temp = 0;//定位
		for (int i = 0;i < order.length(); i++){
			if(Character.isUpperCase(order.charAt(i))){
				sb.insert(i+temp, "_");
				temp += 1;
			}
		}
		sb.append(" ").append(sort);
		return sb.toString(); 
	}
}
